package com.hmall.controller;


import com.hdmall.business.common.annotation.LoginRequired;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.model.MallProductForwardStock;
import com.hmall.model.SysUser;
import com.hmall.service.DealerService;
import com.hmall.service.MallProductPlanService;
import com.hmall.util.TokenUtil;
import com.hmall.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import java.util.*;

/**
 * @Author  zhoutao
 * @Date 2018/11/8 11:30
 * @Param
 * @return
 * @Description //
 */
@RestController
@RequestMapping("/dealer/")
@Api(value = "办事处接口", description = "办事处客户端的接口")
public class DealerController {

    private final JedisPool jedisPool;

    TokenUtil tokenUtil = new TokenUtil();

    private final MallProductPlanService mallProductPlanService;

    private final DealerService dealerService;

    @Autowired
    public DealerController(JedisPool jedisPool, MallProductPlanService mallProductPlanService, DealerService dealerService) {
        this.jedisPool = jedisPool;
        this.mallProductPlanService = mallProductPlanService;
        this.dealerService = dealerService;
    }

    /*Tips：
    * 后期可以优化为办事处用户自能看自己办事处绑定的人员信息，以防止手动输入编号查询出结果
    * */

    /**
     * @Date 2018/11/8 11:31
     * @Param [token]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.DealerUserVo>>
     * @Description // 获得业务员信息
     */
    @LoginRequired
    @GetMapping("getSalesManList")
    @ApiOperation(value = "获得业务员列表", notes = "用在业务员个人中心里")
    public ServerResponse<List<DealerUserVo>> getSalesManInformation(String token) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.getSalesManInformation(user.getUserId());
    }

    /**
     * @Date 2018/11/8 11:31
     * @Param [username, password]
     * @return com.hmall.common.ServerResponse<java.util.Map<java.lang.String,java.lang.String>>
     * @Description // //后台登录  没有PC端  redis冲突问题
     */
    @PostMapping("backLogin")
    @ApiOperation(value = "后台人员登录")
    public ServerResponse<Map<String, String>> backLogin(String username, String password){

        return dealerService.backLogin(username, password);
    }

    /**
     * @Date 2018/11/8 11:32
     * @Param [token, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description //  //办事处客户列表
     */
    @LoginRequired
    @GetMapping("listCustomerUser")
    @ApiOperation(value = "客户的用户列表")
    public ServerResponse<PageVo<CustomerNomalUserVo>> listCustomerUser(String token, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.listCustomerUser(user.getUserId(), pageNum, pageSize);
    }

    /**
     * @Date 2018/11/8 11:32
     * @Param [token, customerUserId]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.CustomerDetialVo>
     * @Description // 办事处客户详情
     */
    @LoginRequired
    @GetMapping("CustomerDetial")
    @ApiOperation(value = "客户详情")
    public ServerResponse<CustomerDetialVo> customerDetail(String token, Integer customerUserId) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.customerDetail(user.getUserId(), customerUserId);
    }

    /**
     * @Date 2018/11/8 11:32
     * @Param [token, customerId]
     * @return com.hmall.common.ServerResponse
     * @Description // 设置是否是星标客户  一个业务员绑定一个客户（公司）
     */
    @LoginRequired
    @GetMapping(value = "changeStar")
    @ApiOperation(value = "切换星标客户状态")
    public ServerResponse changeStar(String token, Integer customerId) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.changeStar(user.getUserId(), customerId);
    }

    /**
     * @Date 2018/11/8 11:32
     * @Param [token, fuzzyModel, shopId, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 根据批号模糊匹配
     */
    @LoginRequired
    @GetMapping("competeByFuzzyModel")
    @ApiOperation(value = "根据批号模糊匹配出产品列表")
    public ServerResponse<PageVo<ShortCompete>> competeByFuzzyModel(String token, String fuzzyModel, @RequestParam(value = "shopId", defaultValue = "1") Integer shopId,
                                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.competeByFuzzyModel(fuzzyModel, shopId, pageNum, pageSize);
    }


    /**
     * @Date 2018/11/8 11:33
     * @Param [token, customerUserId, status, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 即时订单管理（普通订单）  1.客户 2.状态
     */
    @LoginRequired
    @GetMapping("listNomalOrderList")
    @ApiOperation(value = "普通订单列表", notes = "customerUserId不传 该办事员的全客户,status:和页面名称对应 全部，待审核，待发货(付款凭证未上传，付款凭证未审核 合并到待发货)，已发货，交易完成，已取消，退换货，申诉，差评，拿样")
    public ServerResponse<Object> listNormalOrderList(String token, Integer customerUserId, String status, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {

        
        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        
        return dealerService.listNormalOrderList(user.getUserId(), customerUserId, status, pageNum, pageSize);
    }

    /**
     * @Date 2018/11/8 11:33
     * @Param [token, orderNo, status]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.OrderDetialVo>
     * @Description // 订单详情
     */
    @LoginRequired
    @GetMapping("getOrderDetial")
    @ApiOperation(value = "订单详情页")
    public ServerResponse<Object> getOrderDetail(String token, Long orderNo, String status) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }
        //如果这个订单不是这个办事处的无法查看

        //因为数据库库没有差评，申诉的状态，前端传过来状态
        return dealerService.getOrderDetail(user.getUserId(), orderNo, status, null);
    }

    @LoginRequired
    @PostMapping("createSubOrder")
    @ApiOperation(value = "创建子订单", notes = "支持批量创建，里面带上opinion， 2018/12/3 json串需要加入color")
    public ServerResponse createSubOrder(String token, Long orderNo, String subOrderJsonStr) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        return dealerService.createSubOrder(user.getUserId(), orderNo, subOrderJsonStr);
    }
    @LoginRequired
    @PostMapping("deleteSubOrder")
    @ApiOperation(value = "删除子订单")
    public ServerResponse deleteSubOrder(String token, Long orderNo, Long groupNo){

        return dealerService.deleteSubOrder(orderNo, groupNo);
    }
    @LoginRequired
    @GetMapping("getSubOrderDetail")
    @ApiOperation(value = "得到子订单详情")
    public ServerResponse getSubOrderDetail(String token, Long orderNo, Long groupNo, String status) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();

        return dealerService.getSubOrderDetail(user.getUserId(), orderNo, groupNo, status);
    }


    @GetMapping("getConstList")
    @ApiOperation(value = "得到常量列表")
    public ServerResponse getConstList(){

        return dealerService.getConstList();
    }


    /**
     * @Date 2018/11/8 11:33
     * @Param [token, orderNo, jsonOrderItemStr, opinion, status]
     * @return com.hmall.common.ServerResponse
     * @Description // 业务员审核订单
     */
    @LoginRequired
    @PostMapping("changeOrderStatus")
    @ApiOperation(value = "业务员审核订单", notes = "改变订单状态, 1:审核通过 2：审核不通过 3:直接审核通过" + "(\n\njsonStr说明\n" +
            "\n" + "\tInteger productId\n" + "\n" + "\tInteger price\n" +
            "\n" + "\tString grade\n" + "\n" + "\tInteger weight\n" +
            "新加salesOrganization电子销售组织  salesType销售类型 freightPaymentType支付类型 paymentMethods收款方式" +
            " ), 2018/10/19改库存信息 新Json说明：外部Integer productId, String grade, MaterialVo(String materialCode, BigDecimal price BigDecimal weight, String rate, BigDecimal exFactoryPrice)" +
            "2018/11/20改成四个大类分到里面 2018/11/20下午 去除json串转移到子订单里面 ")
    public ServerResponse changeOrderStatus(String token, Long orderNo, String opinion, Integer status) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.changeOrderStatus(user.getUserId(), orderNo, opinion, status);
    }

    /**
     * @Date 2018/11/8 11:33
     * @Param [token, planNo, jsonPlanItemStr, opinion, status]
     * @return com.hmall.common.ServerResponse
     * @Description // 业务员审核计划单
     */
    @LoginRequired
    @PostMapping("changePlanStatus")
    @ApiOperation(value = "业务员审核计划单", notes = "1.提交审核，2.审核驳回 3.保存\n\njsonStr说明\n" +
            "\n" + "\tInteger productId\n" + "\n" + "\tString grade\n" + "\n" + "\tInteger weight\n")
    public ServerResponse changePlanStatus(String token, Long planNo, String jsonPlanItemStr, String opinion, Integer status) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.changePlanStatus(planNo, jsonPlanItemStr, opinion, status);
    }


    /**
     * @Date 2018/11/8 11:34
     * @Param [token, customerUserId, status, pageNum, pageSize]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.PageVo>
     * @Description // 计划列表//对于后台来说 待审核 ——1审核中 ——5
     */
    @LoginRequired
    @GetMapping("listPlanList")
    @ApiOperation(value = "计划列表", notes = "1:全部 2：审核中 3：审核通过 4：审核驳回 6:新建计划 7:待审核 2018-9-11新加")
    public ServerResponse<PageVo<BackPlanVo>> listPlanList(String token, Integer customerUserId, Integer status, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.listPlanList(user.getUserId(), customerUserId, status, pageNum, pageSize);
    }
    @LoginRequired
    @GetMapping("getPlanDetail")
    @ApiOperation(value = "计划详情")
    public ServerResponse<BackPlanDetial> getPlanDetail(String token, Long planNo) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.getPlanDetail(planNo);
    }
    @LoginRequired
    @PostMapping("createRemark")
    @ApiOperation(value = "根据改变计划item列表生成备注",notes = "规定productId = 0表示产品被删除\n\njsonStr说明\n" +
            "\n" + "\tInteger planItemId\n" + "\n" + "\tInteger productId\n" +
            "\n" + "\tString grade\n" + "\n" + "\tInteger weight\n")
    public ServerResponse createRemark(String token, String oldPlanListStr, String newBackPlanListStr) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.createRemark(oldPlanListStr, newBackPlanListStr);
    }

    @LoginRequired
    @GetMapping("listCustomer")
    @ApiOperation(value = "客户列表（公司）")
    public ServerResponse<PageVo<CustomerVo>> listCustomer(String token, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.listCustomer(user.getUserId(), pageNum, pageSize);
    }

    @LoginRequired
    @PostMapping("createProductPlan")
    @ApiOperation(value = "业务员帮助创建生产计划", notes = "\n" +
            "\tInteger productId\n" + "\n" + "\tString grade\n" + "\n" + "BigDecimal amount")
    public ServerResponse createProductPlan(String token, Integer userId, String productListJsonStr, String remark, @RequestParam(value = "submitPerson", defaultValue = "2") Integer submitPerson) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return mallProductPlanService.createProductPlan(userId, productListJsonStr, remark, submitPerson);
    }
    @LoginRequired
    @PostMapping("createOrder")
    @ApiOperation(value = "业务员帮助创建订单", notes = "配送方式1代表自提 2代表华鼎配送\n " + "jsonStr说明\n" +
            "\n" + "\tInteger productId\n" + "\n" + "\tBigDecimal price\n" +
            "\n" + "\tString grade\n" + "\n" + "\tBigDecimal weight\n")
    public ServerResponse createOrder(String token, String productListStr, String opinion, Integer customerUserId, Integer shippingId, Integer distCode, Integer transportId) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.createOrder(productListStr, opinion, customerUserId, shippingId, distCode, transportId);
    }

    /**
     * @Date 2018/11/8 13:02
     * @Param [token, orderItemJsonStr, fufillmentNo, address]
     * @return com.hmall.common.ServerResponse
     * @Description // 发货
     */
    @LoginRequired
    @PostMapping("sendOrder")
    @ApiOperation(value = "业务员根据订单发货",notes = "jsonStr说明\n" +
            "\n" + "\tInteger orderItemId\n" + "\tBigDecimal weight\n, 2018.9.12对于自提的订单加入发货地址的选择" )
    public ServerResponse sendOrder(String token, String orderItemJsonStr, String fufillmentNo, String address) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.sendOrder(orderItemJsonStr, fufillmentNo, address);
    }
    @LoginRequired
    @GetMapping("getOrderFilter")
    @ApiOperation(value = "办事处获得该用户的订单各个状态的数目")
    public ServerResponse<List<BackOrderFilter>> getOrderFilter(String token, Integer customerUserId) throws Exception {

        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        return dealerService.getOrderFilter(user.getUserId(), customerUserId);
    }
    @LoginRequired
    @GetMapping("getCustomerInformation")
    @ApiOperation(value = "办事处获得某个用户绑定的公司的信息", notes = "目前返回信息1.赊账额度2.账期3.公司类型（1表示账期用户0表示现金用户）")
    public ServerResponse getCustomerInformation(String token, Integer customerUserId) throws Exception {

        Integer userId = customerUserId;
        SysUser user = tokenUtil.tokenToUser(jedisPool, token).getData();
        if(null == user.getDeptId()) {
            return ServerResponse.createByErrorMessage("该用户不是后台账号");
        }

        if(null == customerUserId){
            userId = user.getUserId();
        }
        return dealerService.getCustomerInformation(userId);
    }

    /**
     * @Date 2018/11/8 13:03
     * @Param [token, customerId]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.TimeOutSendVo>>
     * @Description // 得到公司的超时的发货列表
     */
    @LoginRequired
    @GetMapping("getTimeOutSendList")
    @ApiOperation(value = "得到公司超时的发货列表")
    public ServerResponse<List<TimeOutSendVo>> getTimeOutSendList(String token, Integer customerId) {

        return dealerService.getTimeOutSendList(customerId);
    }

    @GetMapping("getOrderDetailMessage")
    @ApiOperation(value = "订单详情提示信息")
    public ServerResponse getOrderDetailMessage(Integer customerId){

        return dealerService.getOrderDetailMessage(customerId);
    }

    /**
     * @Author zhoutao
     * @Description // 办事处获得产品列表包含库存
     * @Date 2018/10/12 9:25
     * @Param
     * @return
     **/
    @LoginRequired
    @GetMapping("getProductStockList")
    @ApiOperation("获得产品库存列表")
    public ServerResponse<PageVo<MallProductForwardStock>> getProductStockList(String token, String materialCode, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum,
                                                                               @RequestParam(defaultValue = "10", value = "pageSize") Integer pageSize){

        return dealerService.getProductStockList(materialCode, pageNum, pageSize);
    }

    @LoginRequired
    @GetMapping("getProductMaterialList")
    @ApiOperation("获得物料编码的搜索列表")
    public ServerResponse<List<String>> getProductMaterialList(String token, String materialCode){

        return dealerService.getProductMaterialList(materialCode);
    }
    @LoginRequired
    @GetMapping("getProductForwardStockInformation")
    @ApiOperation(value = "单独得到产品库存信息", notes = "单独查询")
    public ServerResponse<List<MallProductForwardStock>> getProductForwardStockInformation(String token, String model, String twisting, String grade, String color){

        return dealerService.getProductForwardStockInformation(model, twisting, grade, color);
    }
    @LoginRequired
    @PostMapping(value = "getBatchProductForwardStockInformation")
    @ApiOperation(value = "批量得到产品库存信息", notes = "批量查询,json传入model,grade,twisting, 2018/12/3加了color字段")
    public ServerResponse<List<MallProductForwardStockVo>> getBatchProductForwardStockInformation(String token, String productAttrJson){

        return dealerService.getBatchProductForwardStockInformation(productAttrJson);
    }

    @LoginRequired
    @GetMapping(value = "getProductListByMaterialCode")
    @ApiOperation("根据物料编码得到产品列表")
    public ServerResponse getProductListByMaterialCode(String token, String materialCode, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){

        return dealerService.getProductListByMaterialCode(materialCode, pageNum, pageSize);
    }


}
